/* 
 * File:   referencable.hpp
 * Author: gustavo
 *
 * Created on August 27, 2012, 1:32 AM
 */

#ifndef REFERENCABLE_HPP
#define	REFERENCABLE_HPP

namespace imp {

	class Referenceable {
	protected:

		Referenceable() {
			ref = new int;
			(*ref) = 0;
		};

		Referenceable(const Referenceable& r) {
			__init();
		};

		~Referenceable() {
			if ((*ref) > 0) {
				(*ref)--;
			} else {
				delete ref;
			}
		}

		bool isRef() {
			return ( (*ref) > 0);
		}

		int makeReferenceTo(const Referenceable * r) {

			if (isRef()) {
				unRef();
			}

			delete ref;
			ref = 0;

			ref = r->ref;
			(*ref)++;
		}

		void unRef() {
			if ((*ref) > 0) {
				(*ref)--;
			}
			__init();
		}
	private:

		void __init() {
			this->ref = new int;
			(*ref) = 0;
		}

	private:
		int * ref;

	};
}


#endif	/* REFERENCABLE_HPP */

